import 'package:base_plugin/base_plugin.dart';
import 'package:flutter/material.dart';

mixin SearchDataMapMixin<D, T> on BaseProvider<D> {
  TextEditingController searchController = TextEditingController();
  FocusNode searchFocusNode = FocusNode();
  Map<String, List<T>> searchData = {};

  @override
  void initState() {
    super.initState();
    searchController.addListener(_handleSearchInput);
  }

  void _handleSearchInput() {
    update();
  }

  void unFocus() {
    searchFocusNode.unfocus();
  }

  void sortGroupToMap(List<T> list,
      {int sort(T a, T b),
      String group(T a),
      bool filter(T a),
      void itemBefore(Map<String, List<T>> a, T b)}) {
    list.sort(sort);
    for (final item in list) {
      if (filter == null || (filter != null && filter(item))) {
        if (itemBefore != null) {
          itemBefore(searchData, item);
        }
        final firstName = group(item);
        if (searchData[firstName] == null) {
          searchData[firstName] = [item];
        } else {
          searchData[firstName].add(item);
        }
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    searchController.dispose();
    searchFocusNode.dispose();
  }
}
